package com.major.dawn.leetCode.integer;


import java.util.HashSet;

public class solution {

    public int integerBreak(int n) {
        int[] dp = new int[n + 1];

        for (int i = 2; i <= n; i++) {
            int max = 0;
            for (int j = 1; j < i; j++) {
                max = Math.max(max, Math.max(j * (i - j), j * dp[i - j]));
            }
            dp[i] = max;
        }
        return dp[n];
    }


    public int lengthOfLongestSubstring(String s) {
        int i = 0;
        int flag = 0;
        int length = 0;
        int result = 0;
        while (i < s.length()) {
            int pos = s.indexOf(s.charAt(i),flag);
            if (pos < i) {
                if (length > result) {
                    result = length;
                }
                if (result >= s.length() - pos - 1) {
                    return result;
                }
                length = i - pos - 1;
                flag = pos + 1;
            }
            length++;
            i++;
        }
        return length;
    }


    public int lengthOfLongestSubstring2(String s) {

        if(s==null&& s.equals("")){
            return 1;
        }
        char[] sChars = s.toCharArray();
        int charsLen = sChars.length;

        int longest = 0;
        int head = 0;
        int tail = 0;
        HashSet charSet = new HashSet();

        while (tail<charsLen){
            int currLongest = tail -head ;

            for (int i = tail; i < charsLen; i++) {
                tail = i +1;

                char sChar = sChars[i];
                if(!charSet.contains(sChar)){
                    charSet.add(sChar);
                    currLongest++;
                }else{
                    int indexOf = s.indexOf(sChar,head);
                    for (int j = head; j < indexOf; j++) {
                        charSet.remove(sChars[j]);
                    }
                    head = indexOf+1;
                    break;
                }
            }
            longest = Math.max(longest, currLongest);

        }
        return longest;
    }

    public static void main(String[] args) {
        solution solution = new solution();
        int aab = solution.lengthOfLongestSubstring2("abcabcbb");
        System.out.println(aab);
    }


}
